package com.account;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import mybatis.mapper.UserDao;
import mybatis.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.json.JSONObject;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;

public class AddAccount extends HttpServlet {
    /**
     * 增加新账号
     *
     * @param req  获取参数 account password1 password2 platform
     * @param resp 返回
     * @throws ServletException servlet错误
     * @throws IOException      io
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //        ------ 接收 ------
        Enumeration<String> params = req.getParameterNames();
        String account = req.getParameter("account");
        //        ------ 验证 ------
        if (account == null) {
            HashMap<String, Object> result = new HashMap<>();
            result.put("code", "0");
            result.put("message", "请输入账号");
            resp.setContentType("text/json; charset=utf-8");
            JSONObject content = new JSONObject(result);
            PrintWriter writer = resp.getWriter();
            writer.println(content);
            return;
        }
        //        ------ 处理 ------
        //        数据库连接
        SqlSession session = MybatisUtils.getSqlSession();
        UserDao userMapper = session.getMapper(UserDao.class);
        //        组织参数
        HashMap<String, Object> user = new HashMap<>();
        while (params.hasMoreElements()) {
            String name = params.nextElement();
            user.put(name, req.getParameter(name));
        }
        Date now = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String nowStr = ft.format(now);
        user.put("createTime", nowStr);
        //        插入数据
        userMapper.addAccount(user);
        session.commit();
        session.close();
        HashMap<String, Object> ret = new HashMap<>();
        ret.put("code", 1);
        ret.put("message", "success");
        resp.setContentType("text/json; charset=utf-8");
        JSONObject content = new JSONObject(ret);
        PrintWriter writer = resp.getWriter();
        writer.println(content);
    }
}
